import 'dart:io';

import 'package:file_picker/file_picker.dart';
import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:icoreader/models/icon.dart';
import 'package:shirne_dialog/shirne_dialog.dart';

import 'icon.dart';

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  IconModel model = IconModel();
  bool isLoading = true;

  @override
  void initState() {
    super.initState();
    model.init().then((v) {
      setState(() {
        isLoading = false;
      });
    });
  }

  void openFile() {
    if (kIsWeb) {
      _loadFileMobile();
    } else if (Platform.isAndroid || Platform.isIOS) {
      _loadFileMobile();
    } else if (Platform.isWindows || Platform.isLinux || Platform.isLinux) {
      _loadFileWindow();
    } else {
      MyDialog.of(context).toast('暂不支持该平台');
    }
  }

  void _locateFile(String path) {
    model.placeFile(path).then((v) {
      setState(() {});
    });
  }

  void _loadFileMobile() async {
    FilePickerResult? result =
        await FilePicker.platform.pickFiles(allowedExtensions: ['ttf', 'otf']);

    if (result != null) {
      if (result.files.single.path != null) {
        _locateFile(result.files.single.path!);
      }
    }
  }

  void _loadFileWindow() async {
    const typeGroup = XTypeGroup(
      label: '字体文件',
      extensions: ['ttf', 'otf'],
    );
    final files = await FileSelectorPlatform.instance
        .openFiles(acceptedTypeGroups: [typeGroup]);
    if (files.isNotEmpty) {
      _locateFile(files[0].path);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: isLoading ? const CircularProgressIndicator() : const IconPage(),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: openFile,
        tooltip: 'Open a ttf/otf file',
        child: const Icon(Icons.archive),
      ),
    );
  }
}
